Imports Cdm.DataCore.Entities
Imports Cdm.DataCore.EmployeeSchedule
Imports System.Collections.Generic

Partial Class Case_EmployeeScheduler
    Inherits System.Web.UI.Page

    Dim participantId As Integer
    Dim participantEmployeeId As Integer
    Dim employeeScheduleList As List(Of EmployeeScheduleDisplay)


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        participantId = Convert.ToInt32(Request("id"))
        Me.StatusLabel.Visible = False
        If Not IsPostBack Then
            StartDateTextBox.Text = SundayBefore(DateTime.Now).ToString("MM/dd/yyyy")
            BindRepeaters()
        End If

    End Sub

    Private Function SundayBefore(ByVal firstDate As DateTime) As DateTime
        Select Case firstDate.DayOfWeek
            Case DayOfWeek.Sunday
                Return firstDate.Date()
            Case DayOfWeek.Monday
                Return firstDate.AddDays(-1).Date()
            Case DayOfWeek.Tuesday
                Return firstDate.AddDays(-2).Date()
            Case DayOfWeek.Wednesday
                Return firstDate.AddDays(-3).Date()
            Case DayOfWeek.Thursday
                Return firstDate.AddDays(-4).Date()
            Case DayOfWeek.Friday
                Return firstDate.AddDays(-5).Date()
            Case DayOfWeek.Saturday
                Return firstDate.AddDays(-6).Date()
        End Select

    End Function

    Private Sub BindRepeaters()
        Dim employeeList As List(Of ParticipantEmployee) = ParticipantEmployee.ListByParticipant(participantId)
        Dim weekStartDate As DateTime = Convert.ToDateTime(StartDateTextBox.Text)
        employeeScheduleList = EmployeeScheduleDisplay.ListByParticipantForWeek(participantId, weekStartDate)
        Me.EmployeeRepeater.DataSource = employeeList
        Me.EmployeeRepeater.DataBind()

        Me.ScheduleRepeater.DataSource = employeeList
        Me.ScheduleRepeater.DataBind()
        'SetHeaderLabels(weekStartDate)
    End Sub

    Private Sub SetHeaderLabels(ByVal startDate As DateTime)
        Dim day1Label As Label = ScheduleRepeater.FindControl("Day1Label")
        Dim day2Label As Label = ScheduleRepeater.FindControl("Day2Label")

        day1Label.Text = startDate.ToString("mmm d")
        day2Label.Text = startDate.AddDays(1).ToString("mmm d")

    End Sub

    Private Sub SetHeaderLabels(ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs)
        Dim day1Label As Label = e.Item.FindControl("Day1Label")
        Dim day2Label As Label = e.Item.FindControl("Day2Label")
        Dim day3Label As Label = e.Item.FindControl("Day3Label")
        Dim day4Label As Label = e.Item.FindControl("Day4Label")
        Dim day5Label As Label = e.Item.FindControl("Day5Label")
        Dim day6Label As Label = e.Item.FindControl("Day6Label")
        Dim day7Label As Label = e.Item.FindControl("Day7Label")

        Dim weekStartDate As DateTime = Convert.ToDateTime(StartDateTextBox.Text)
        If Not day1Label Is Nothing Then
            day1Label.Text = weekStartDate.ToString("MMM dd")
            day2Label.Text = weekStartDate.AddDays(1).ToString("MMMM d")
            day3Label.Text = weekStartDate.AddDays(2).ToString("MMMM d")
            day4Label.Text = weekStartDate.AddDays(3).ToString("MMMM d")
            day5Label.Text = weekStartDate.AddDays(4).ToString("MMMM d")
            day6Label.Text = weekStartDate.AddDays(5).ToString("MMMM d")
            day7Label.Text = weekStartDate.AddDays(6).ToString("MMMM d")
        End If

        Dim yr1 As String = weekStartDate.Year.ToString()
        Dim yr2 As String = weekStartDate.AddDays(6).Year.ToString()
        If yr1 = yr2 Then
            YearLabel.Text = String.Concat(yr1, " Schedule")
        Else
            YearLabel.Text = String.Concat(yr1, "/", yr2, " Schedule")
        End If

    End Sub

    Protected Sub ScheduleRepeater_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles ScheduleRepeater.ItemDataBound
        Dim empSchedule As ASP.case_employeeweeklyschedule_ascx = e.Item.FindControl("WeeklyScheduleControl")
        Dim pe As ParticipantEmployee = e.Item.DataItem
        If Not pe Is Nothing Then
            Me.participantEmployeeId = pe.ParticipantEmployeeID
            empSchedule.SetDataSource(employeeScheduleList.FindAll(AddressOf MatchEmployee))
        Else
            SetHeaderLabels(e)
        End If
    End Sub

    Private Function MatchEmployee(ByVal es As EmployeeScheduleDisplay) As Boolean
        Return es.ParticipantEmployeeId = Me.participantEmployeeId
    End Function

    Protected Sub NextWeekButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles NextWeekButton.Click
        Dim newStartDate As DateTime = Convert.ToDateTime(StartDateTextBox.Text)
        newStartDate = newStartDate.AddDays(7)
        StartDateTextBox.Text = SundayBefore(newStartDate).ToString("MM/dd/yyyy")
        BindRepeaters()
    End Sub

    Protected Sub PreviousWeekButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles PreviousWeekButton.Click
        Dim newStartDate As DateTime = Convert.ToDateTime(StartDateTextBox.Text)
        newStartDate = newStartDate.AddDays(-7)
        StartDateTextBox.Text = SundayBefore(newStartDate).ToString("MM/dd/yyyy")
        BindRepeaters()
    End Sub

    Protected Sub GoButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles GoButton.Click

        Dim newStartDate As DateTime = DateTime.Now
        If IsDate(StartDateTextBox.Text) Then
            newStartDate = Convert.ToDateTime(StartDateTextBox.Text)
        End If
        StartDateTextBox.Text = SundayBefore(newStartDate).ToString("MM/dd/yyyy")
        BindRepeaters()
    End Sub

    Protected Sub EditEmployeeTimeSheet(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkButton As LinkButton = sender
        Me.EmployeeIdLabel.Text = lnkButton.CommandArgument
        Me.StartDateMenuTextBox.Text = Me.StartDateTextBox.Text
        BindWeeklySchedule()
        BindDateDropDown(Convert.ToDateTime(Me.StartDateMenuTextBox.Text), Me.AddStartDateDropDown)
        BindDateDropDown(Convert.ToDateTime(Me.StartDateMenuTextBox.Text), Me.AddEndDateDropDown)
        Me.ModalPopupEditSchedule.Show()
    End Sub

    Private Sub BindWeeklySchedule()
        Dim employeeId As Integer = Convert.ToInt32(EmployeeIdLabel.Text)
        Dim startDate As DateTime = Convert.ToDateTime(StartDateMenuTextBox.Text)
        Me.WeeklyScheduleGridView.DataSource = Cdm.DataCore.EmployeeSchedule.EmployeeSchedule.ListByEmployeeForWeek(employeeId, startDate)
        WeeklyScheduleGridView.DataBind()
    End Sub

    Protected Sub WeeklyScheduleGridView_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles WeeklyScheduleGridView.RowCancelingEdit
        WeeklyScheduleGridView.EditIndex = -1
        BindWeeklySchedule()
        ModalPopupEditSchedule.Show()
    End Sub

    Protected Sub WeeklyScheduleGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles WeeklyScheduleGridView.RowDataBound
        Dim currentSchedule As EmployeeSchedule = e.Row.DataItem
        Dim startDateDropDown As DropDownList = e.Row.FindControl("EditStartDateDropDownList")
        If Not startDateDropDown Is Nothing Then
            BindDateDropDown(Convert.ToDateTime(StartDateMenuTextBox.Text), startDateDropDown)
            startDateDropDown.SelectedValue = currentSchedule.StartTime.Date.ToString("MM/dd/yyyy")
        End If
        Dim startTimeDropDown As DropDownList = e.Row.FindControl("EditStartTimeDropDownList")

        If Not startTimeDropDown Is Nothing Then
            startTimeDropDown.SelectedValue = currentSchedule.StartTime.ToString("h:mm tt")
        End If

        Dim endDateDropDown As DropDownList = e.Row.FindControl("EditEndDateDropDownList")
        If Not endDateDropDown Is Nothing Then
            BindDateDropDown(Convert.ToDateTime(StartDateMenuTextBox.Text), endDateDropDown)
            endDateDropDown.SelectedValue = currentSchedule.EndTime.Date.ToString("MM/dd/yyyy")
        End If

        Dim endTimeDropDown As DropDownList = e.Row.FindControl("EditEndTimeDropDownList")

        If Not endTimeDropDown Is Nothing Then
            endTimeDropDown.SelectedValue = currentSchedule.EndTime.ToString("h:mm tt")
        End If


    End Sub

    Private Sub BindDateDropDown(ByVal startDate As DateTime, ByVal ddl As DropDownList)
        Dim alDate As New ArrayList()
        For iDays As Integer = 0 To 6
            alDate.Add(startDate.Date.AddDays(iDays).Date.ToString("MM/dd/yyyy"))
        Next
        ddl.DataSource = alDate
        ddl.DataBind()
    End Sub

    Protected Sub OKButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OKButton.Click
        Me.ModalPopupEditSchedule.Hide()
        Me.StartDateTextBox.Text = Me.StartDateMenuTextBox.Text
        BindRepeaters()
    End Sub

    Protected Sub WeeklyScheduleGridView_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles WeeklyScheduleGridView.RowDeleting
        Try
            Dim scheduleId As Integer = WeeklyScheduleGridView.DataKeys(e.RowIndex)(0)
            EmployeeSchedule.RemoveInstance(EmployeeSchedule.Retrieve(scheduleId))
            ShowStatus("Schedule Item removed")
        Catch ex As Exception
            ShowStatus("Error Removing Schedule: " + ex.Message)
        End Try
        BindWeeklySchedule()
        ModalPopupEditSchedule.Show()
    End Sub

    Protected Sub WeeklyScheduleGridView_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles WeeklyScheduleGridView.RowEditing
        WeeklyScheduleGridView.EditIndex = e.NewEditIndex
        BindWeeklySchedule()
        ModalPopupEditSchedule.Show()
    End Sub

    Protected Sub AddScheduleButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles AddScheduleButton.Click
        Dim addSchedule As New EmployeeSchedule()
        Dim newStartTime As DateTime = Convert.ToDateTime(String.Concat(AddStartDateDropDown.SelectedValue, " ", AddStartTimeDropDown.SelectedValue))
        Dim newEndTime As DateTime = Convert.ToDateTime(String.Concat(AddEndDateDropDown.SelectedValue, " ", AddEndTimeDropDown.SelectedValue))

        If Not ValidateDateEntry(newStartTime, newEndTime, 0) Then Exit Sub

        
        addSchedule.ParticipantEmployeeId = Convert.ToInt32(Me.EmployeeIdLabel.Text)
        addSchedule.StartTime = newStartTime
        addSchedule.EndTime = newEndTime
        addSchedule.ParticipantId = Convert.ToInt32(Request("id"))
        addSchedule.Persist()
        BindWeeklySchedule()
        ShowStatus("New Schedule Added.")
        ModalPopupEditSchedule.Show()
    End Sub

    Private Sub ShowStatus(ByVal msg As String)
        StatusLabel.Text = msg
        StatusLabel.Visible = True
    End Sub

    Private Function ValidateDateEntry(ByVal startTime As DateTime, ByVal endTime As DateTime, ByVal scheduleId As Integer) As Boolean
        If endTime <= startTime Then
            ShowStatus("Please Select an end time that is later than the start time.")
            ModalPopupEditSchedule.Show()
            Return False
        End If

        Dim datesOverlap As Boolean = False
        Dim employeeId As Integer = Convert.ToInt32(EmployeeIdLabel.Text)
        Dim weekStartDate As DateTime = Convert.ToDateTime(StartDateMenuTextBox.Text)
        Dim scheduleList As List(Of EmployeeSchedule) = EmployeeSchedule.ListByEmployeeForWeek(employeeId, weekStartDate)
        For iSched As Integer = 0 To scheduleList.Count - 1
            If startTime <= scheduleList(iSched).EndTime And endTime >= scheduleList(iSched).StartTime Then
                datesOverlap = True
                Exit For
            End If
        Next

        If datesOverlap Then
            ShowStatus("Employee is already scheduled for at least part of the time you have entered.")
            ModalPopupEditSchedule.Show()
            Return False
        End If

        Return True

    End Function

    Protected Sub WeeklyScheduleGridView_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles WeeklyScheduleGridView.RowUpdating
        Try
            Dim updateSchedule As New EmployeeSchedule()
            updateSchedule.ScheduleId = WeeklyScheduleGridView.DataKeys(e.RowIndex)(0)
            Dim startDateDropDown As DropDownList = WeeklyScheduleGridView.Rows(e.RowIndex).FindControl("EditStartDateDropDownList")
            Dim startTimeDropDown As DropDownList = WeeklyScheduleGridView.Rows(e.RowIndex).FindControl("EditStartTimeDropDownList")
            Dim endDateDropDown As DropDownList = WeeklyScheduleGridView.Rows(e.RowIndex).FindControl("EditEndDateDropDownList")
            Dim endTimeDropDown As DropDownList = WeeklyScheduleGridView.Rows(e.RowIndex).FindControl("EditEndTimeDropDownList")
            Dim newStartTime As DateTime = Convert.ToDateTime(String.Concat(startDateDropDown.SelectedValue, " ", startTimeDropDown.SelectedValue))
            Dim newEndTime As DateTime = Convert.ToDateTime(String.Concat(endDateDropDown.SelectedValue, " ", endTimeDropDown.SelectedValue))
            updateSchedule.ParticipantEmployeeId = EmployeeIdLabel.Text
            updateSchedule.ParticipantId = Convert.ToInt32(Request("id"))
            updateSchedule.StartTime = newStartTime
            updateSchedule.EndTime = newEndTime

            EmployeeSchedule.UpdateInstance(updateSchedule)
            ShowStatus("Update Successful.")
            WeeklyScheduleGridView.EditIndex = -1
            BindWeeklySchedule()
            ModalPopupEditSchedule.Show()



        Catch ex As Exception
            ShowStatus("Error Updating Schedule: " + ex.Message)
            ModalPopupEditSchedule.Show()
        End Try
    End Sub
End Class
